import { Game } from '../core/Game';
import { Databus } from '../core/Databus';
import { BilliardGame } from '../game/BilliardGame';
import { WebFrameController } from './WebFrameController';
import { HumanAiController } from './HumanAiController';
import { EventManager } from '../core/EventManager';
const databus = Databus.Instance();

export class GameUserInstance {
  private static instance: GameUserInstance = null as unknown as GameUserInstance;
  public static Instance() {
    if (GameUserInstance.instance) {
      return GameUserInstance.instance;
    }
    GameUserInstance.instance = new GameUserInstance();
    return GameUserInstance.instance;
  }
  constructor() { }

  public updateFrame(deltaTime: number) {
    if (Game.Instance().battleCate.isFrientBattle()) { // 好友对战
      WebFrameController.Instance().updateFrame(deltaTime);
    } else if (Game.Instance().isRobotHitting()) { // 轮到机器人模拟人击球
      HumanAiController.Instance().updateFrame(deltaTime);
    }
  }
  // 开始游戏
  public startGame() {
    if (Game.Instance().battleCate.isFrientBattle()) { // 好友对战
      WebFrameController.Instance().sendGameFirstFrame();
    }
    WebFrameController.Instance().startGame();
    this.startStep();
  }
  // 结束游戏
  public endGame() {
    
  }
  // 开始击球
  public startStep() {
    // 不管是谁击球，都会默认一个击球位置
    const hitball = HumanAiController.Instance().defaultAimPosition(Game.Instance().battleCate, Game.Instance().gameType, Game.Instance().currentStep);
    EventManager.Instance().Emit('HitBallHasChoosed', hitball);
    // 机器人击球计算
    if (Game.Instance().isRobotHitting()) {
      if (BilliardGame.Instance().robotRenShu()) {
        Game.Instance().robotSurrender();
        EventManager.Instance().Emit('EndGame', {});
        return;
      }
      HumanAiController.Instance().computateDeduction(BilliardGame.Instance().isFreeKickBall(),Game.Instance().gameType, Game.Instance().currentStep);
    }
    WebFrameController.Instance().startStepFrame();
  }
  // 结束当前的击球
  public endStep() {
    WebFrameController.Instance().endStepFrame();
  }
  // 是否可以结束击球
  public syncEndStep() {
    if (!Game.Instance().battleCate.isFrientBattle()) return true;
    if (Game.Instance().status.isEnded()) return true;
    if (Game.Instance().isSelftHitBall()) return true;
    // 网络用户，必须接收模拟完成最后一帧的数据【对齐数据】之后，才能结束
    return WebFrameController.Instance().syncStepOverData();
  }
}